var db = require('../config/mongo_database');
var redisClient = require('../config/redis_database').redisClient;
var moment = require('moment');
var tokenManager = require('../config/token_manager');
var logger = require('../config/log4js').logger('access');


// 新增评论
exports.add = function(req, res) {
	var pid = req.body.pid || ''; // 商品号
	var content = req.body.content || ''; // 评论内容

	if(pid=='' || content.trim()=='') return res.sendStatus(403);

	var user = tokenManager.getUser(req);
	var comment = new db.commentModel();

	comment.userid = user.id;
	comment.pid    = pid;
	comment.nick   = user.nick;
	comment.header = user.header;
	comment.content= content;
	comment.save(function(err) {
		logger.error("add[commentModel]: ", err)
		db.commentModel.find({pid: pid, type:'0'}, {'header':1, 'nick':1, 'content':1, created:1}, function(err, comments){
			return res.json(comments);
		}).sort({"created":-1})
	})
};

// 商品评论
exports.post = function(req, res){
	var pid     = req.body.pid || '';     // 商品号
	var orderid = req.body.orderid || ''; // 订单号
	var content = req.body.content || ''; // 评论内容
	var score   = req.body.score || 2;

	if(pid=='' || orderid=='') return res.sendStatus(403);

	db.commentModel.findOne({orderid:orderid}, function(err, data){
		if(null!=data){
			res.sendStatus(405); //已经评论
		}else{
			var comment = new db.commentModel();
			var user = tokenManager.getUser(req);
			comment.userid  = user.id;
			comment.pid     = pid;
			comment.nick    = user.nick;
			comment.header  = user.header;
			comment.content = content;
			comment.orderid = orderid;
			comment.score   = score;
			comment.type = '1';
			comment.save(function(err) {})

			// 更新评价状态
			db.orderModel.update({orderid:orderid}, {$set:{cStatus:'1'}}, function(err){

			})

			// 更新商品评分
			db.postModel.findOne({pid:pid}, function(err, post){
				post.start.a+=score;
				++post.start.b;

				db.postModel.update({pid:pid}, {$set:{start: post.start}}, function(err){
					return res.sendStatus(200);
				})
			})
		}
	})
}


// 查看评论
exports.query = function(req, res) {
	var pid = req.query.pid || ''; // 商品号
	var type = req.query.type || '0'; // 商品号
	db.commentModel.find({pid: pid, type:type}, {'header':1, 'nick':1, 'content':1, created:1}, function(err, comments){
		return res.json(comments);
	}).sort({"created":-1})
}

